package com.vma.jifu.backsys.controller;

/**
 * Created by kitabi on 2017/6/20.
 */

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.sun.xml.internal.rngom.parse.host.Base;
import com.vma.jifu.bizModel.model.Menu;
import com.vma.jifu.bizModel.model.Menu2Staff;
import com.vma.jifu.bizModel.model.Staff;
import com.vma.tools.ReturnsUtil;

import java.util.*;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class StaffController extends BaseController {

    /**
     * 状态、工号查询
     * cPage(*)
     * pSize(*)
     * staff_code
     * status
     */
    public void queryList(){
        try{
            String status = getPara("status");
            String staffCode = getPara("phone");
            int pageNo = getParaToInt("cPage");
            int pageSize = getParaToInt("pSize");



            List<String> param = new ArrayList<String>();
            String condition = "";
            if(status != null && !"".equals(status)){
                condition += "and status = ? ";
                param.add(status);
            }
            if(staffCode != null && !"".equals(staffCode)){
                condition += " and ( phone like ? ";
                param.add("%"+staffCode+"%");

                condition += "or name like ? ";
                param.add("%"+staffCode+"%");

                condition += "or staff_id like ?  )";
                param.add("%"+staffCode+"%");
            }

            Page<Staff> staffList = Staff.dao.paginate(pageNo,pageSize,"select * ","from staff where 1=1 "+condition
                    ,param.toArray());




            Map<String,Object> map = ReturnForm(staffList.getList(),staffList.getTotalRow());
            renderJson(map);
        }catch (Exception e){
            renderJson(ReturnsUtil.returnException("staff.queryList",e));
        }
    }

    public void queryMenuByStaffId() throws Exception {
        try{
            String staffId = getPara("staffId");
            System.out.println(staffId);


            List<Menu> menus = Menu.dao.find("SELECT m.* FROM menu m,menu_2_staff m2s,staff s "+
                    "WHERE m.menu_id = m2s.menu_id "+
                    "AND s.staff_id = m2s.staff_id "+
                    "AND s.staff_id = ? ",staffId);

            renderJson(ReturnsUtil.returnSuccess(menus));
        }catch (Exception e){
            renderJson(ReturnsUtil.returnException("staff.queryMenuByStaffId",e));
        }

    }

    public void queryMenuList() throws Exception {
        try{

            List<Menu> menus = Menu.dao.find("SELECT m.* FROM menu m "

            );

            renderJson(ReturnsUtil.returnSuccess(menus));
        }catch (Exception e){
            renderJson(ReturnsUtil.returnException("staff.queryMenuByStaffId",e));
        }

    }


    public void 	updateMenuById() throws Exception {
        try{

            String menu = getPara("menuList");
            String staffId = getPara("staffId");


            List <Menu2Staff> menu2Staffs= Menu2Staff.dao.find("select* from menu_2_staff where staff_id="+staffId);

            for (Menu2Staff temps : menu2Staffs){
                temps.delete();
            }

            //然后根据menulist新增

            String[] menulist = menu.split(",");
            for(String id:menulist) {
                Menu2Staff menu2Staff = new Menu2Staff();
                menu2Staff.setMenuId(Integer.valueOf(id)).setStaffId(Integer.valueOf(staffId)).save();
            }

            renderJson(ReturnsUtil.returnSuccess("添加成功"));
        }catch (Exception e){
            renderJson(ReturnsUtil.returnException("staff.queryMenuByStaffId",e));
        }

    }



    /**
     * 删除管理员(不能删除当前登陆工号)
     * param:
     * staffId(*)
     */
    public void delete(){
        try{
            String staffId  = getPara("staffId");
            Staff.dao.deleteById(staffId);
            renderJson(ReturnsUtil.returnSuccess("删除成功"));
        }catch (Exception e){
            renderJson(ReturnsUtil.returnException("staff.delete",e));
        }

    }

    /**
     * 批量删除管理员
     * staffIds(*)
     * eg:{
     *     staffIds:1,2,3
     * }
     */
    public void deleteBatch(){
        try{
//            String staffIds = getPara("staffIds");
//            List<String> ids = new ArrayList<String>();
//            JFinalTool.getInList(ids, staffIds);
//            for(String id:ids){
//                Staff.dao.deleteById(id);
//            }
            renderJson(ReturnsUtil.returnSuccess("删除成功"));
        }catch (Exception e){
            renderJson(ReturnsUtil.returnException("staff.deleteBatch",e));
        }

    }

    /**
     * 新增管理员
     * param
     * staffCode(*)
     * name(*)
     * phone(*)
     * password(*)、无需加密
     */
    public void add(){
        try{
            String staffCode = getPara("staffCode");
            String name = getPara("name");
            String password = getPara("password");
            String phone = getPara("phone");
            new Staff().set("staff_code", staffCode).set("name", name).setStatus(1).setCreateDate(new Date())
                    .set("phone", phone).set("password", password).save();
//		new Staff().set();
//			getSession.("staffCode", staffCode);
            renderJson(ReturnsUtil.returnSuccess("添加成功"));
        }catch (Exception e){
            renderJson(ReturnsUtil.returnException("staff.add",e));
        }

    }

    /**
     * 更新管理员信息（基础信息及密码，密码不需要加密）
     * staffId(*)
     * name
     * password
     * phone
     */
    public void update(){
        try{
            String staffId = getPara("staffId");
            String name = getPara("name");
            String password = getPara("password");
            String phone = getPara("phone");
            String status = getPara("u_status");
            Staff staff = Staff.dao.findById(staffId);
            if(name != null && !"".equals(name)){
                staff.set("name", name);
            }
            if(password != null && !"".equals(password)){
                staff.set("password", password);
            }
            if(phone !=null && !"".equals(phone)){
                staff.set("phone", phone);
            }
            if(status != null && !"".equals(status)){
                staff.setStatus(Integer.valueOf(status));
            }
            staff.update();
            renderJson(ReturnsUtil.returnSuccess("更新成功"));
        }catch (Exception e){
            renderJson(ReturnsUtil.returnException("staff.update",e));
        }

    }


    public void login(){
        String staffCode = getPara("staffCode");
        String password = getPara("password");
        List<Staff> staffs = Staff.dao.find("select * from staff where staff_code = ?",staffCode);

        if (staffs == null || staffs.size() ==0){
            renderJson(ReturnsUtil.returnFail("工号不存在","-1"));//-1工号不存在
        }else if(staffs.size() > 1){
            renderJson(ReturnsUtil.returnFail("工号信息异常","-2"));
        }else {
            if(staffs.get(0).getStatus().toString().equals("1")){
                if(password.equals(staffs.get(0).getPassword())){
//				getSession().setAttribute("staffId",staffs.get(0).getStaffId());

                    staffs.get(0).setLoginDate(new Date()).update();//更新日志

                    setSessionAttr("staffId",staffs.get(0).getStaffId().toString());
                    renderJson(ReturnsUtil.returnSuccess(staffs.get(0).getStaffId()));
                }else {
                    renderJson(ReturnsUtil.returnFail("密码错误","-2"));
                }
            }else {
                renderJson(ReturnsUtil.returnFail("工号禁用","-2"));
            }

        }
    }


    public void toLogin(){

        String Session = getSessionAttr("staffId");
        if(Session != null && !"".equals(Session)){


            Staff staff = Staff.dao.findById(Session);

            setSessionAttr("LOGIN_USER_INFO",staff);


            setAttr("staffCode",staff.getStaffCode());
            render("/newshop/index/index.jsp");
        }else {

            renderVelocity("/newshop/login/index.html");
        }
    }

}

